package polygon.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/** @author Mike Mirzayanov */
public class StreamUtil {
    public static byte[] getContent(InputStream inputStream, int maxSize) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            byte[] chunk = new byte[65536];
            while (true) {
                int size = inputStream.read(chunk);
                if (size == -1) {
                    break;
                }
                outputStream.write(chunk, 0, size);
                if (outputStream.size() > maxSize) {
                    throw new IOException("Data exceeds " + maxSize + " bytes");
                }
            }
        } finally {
            inputStream.close();
        }
        return outputStream.toByteArray();
    }

    public static void transfer(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] chunk = new byte[65536];
        try {
            while (true) {
                int size = inputStream.read(chunk);
                if (size == -1) {
                    break;
                }
                outputStream.write(chunk, 0, size);
            }
        } finally {
            inputStream.close();
        }
    }
}
